package com.yyf.blogapi.config;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.yyf.blogapi.handler.NeedLoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;

@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
    @Resource
    NeedLoginInterceptor needLoginInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:8080");
    }

    //在mvc配置中添加拦截器，并添加需要拦截的接口
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(needLoginInterceptor)
                .addPathPatterns("/admin/all")
                .addPathPatterns("/articles/publish")
                .addPathPatterns("/comments/create/change");
    }

    //Long类型的数据，如果我们在后端将结果序列化为json，直接传给前端的话，在Long长度大于17位时会出现精度丢失的问题。
    //java中得long能表示的范围比js中number大,也就意味着部分数值在js中存不下(变成不准确的值)
    //
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance();
        serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
        serializeConfig.put(Long.class, ToStringSerializer.instance);
        serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
        fastJsonConfig.setSerializeConfig(serializeConfig);
        converter.setFastJsonConfig(fastJsonConfig);
        converters.add(converter);
    }
}
